package com.ruoyi.web.controller.business.rule;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruoyi.business.base.PageParam;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.system.domain.vo.SysDeptVo;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.web.controller.business.rule.vo.JbOpportunityRulesVO;
import com.ruoyi.web.controller.system.SysDeptController;
import com.ruoyi.web.core.JoController;
import com.ruoyi.web.core.JoR;
import com.ruoyi.web.core.tool.ColumnUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.rule.domain.JbOpportunityRules;
import com.ruoyi.business.rule.service.JbOpportunityRulesService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 商机规则 Controller
 *
 * @author ruoyi
 * @date 2024-10-11
 */
@Api("商机规则")
@RestController
@RequestMapping("/opportunity_rules")
public class JbOpportunityRulesController extends JoController
{
    @Autowired
    private JbOpportunityRulesService service;
    @Autowired
    private ISysDeptService deptService;

    /**
     * 查询商机规则列表
     */
    @ApiOperation("查询商机规则列表")
    @GetMapping("/list")
    public TableDataInfo list(PageParam page, JbOpportunityRules jbOpportunityRules)
    {
        LambdaQueryWrapper<JbOpportunityRules> select = new LambdaQueryWrapper<>();
        IPage<JbOpportunityRules> iPage = service.page(page.b(), select);
        return JoR.rows(iPage);
    }

    /**
     * 查询线下渠道商机规则列表
     *
     * @param page    分页查询对象
     * @param sysDept 系统部门对象
     * @return
     */
    @ApiOperation("查询线下渠道商机规则列表")
    @GetMapping("/listAllByOffline")
    @SneakyThrows
    public AjaxResult listAllByOffline(PageParam page, SysDept sysDept)
    {
        return findAllRules(page, sysDept, Constants.OFFLINE_OPPORTUNITY);
    }

    /**
     * 查询线上公共商机规则列表
     *
     * @param page    分页查询对象
     * @param sysDept 系统部门对象
     * @return
     */
    @ApiOperation("查询线上公共商机规则列表")
    @GetMapping("/listAllByPublic")
    @SneakyThrows
    public AjaxResult listAllByPublic(PageParam page, SysDept sysDept)
    {
        return findAllRules(page, sysDept, Constants.ONLINE_PUBLIC_OPPORTUNITY);
    }


    /**
     * 线上线下 公用查询方法
     *
     * @param page      分页对象
     * @param sysDept   部门对象
     * @param rulesCode 规则编码
     * @return
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     */
    private AjaxResult findAllRules(PageParam page, SysDept sysDept, String rulesCode) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException
    {

        sysDept.setDeptName(page.getKeyword());
        List<SysDept> depts = deptService.selectDeptList(sysDept);

        List<JbOpportunityRulesVO> list = BeanUtil.copyToList(depts, JbOpportunityRulesVO.class);

        //获取数据集
        List<Long> ids = ids(list, ColumnUtil.F(JbOpportunityRulesVO::getDeptId));
        List<JbOpportunityRules> rules = service.listAllByDeptIds(ids, rulesCode);

        //规则
        Map map = kv(
                ColumnUtil.F(JbOpportunityRules::getDeptId),
                ColumnUtil.F(JbOpportunityRules::getExecutionContent),
                rules
        );
        toKey(list, map,
                ColumnUtil.F(JbOpportunityRulesVO::getDeptId),
                ColumnUtil.F(JbOpportunityRulesVO::getExecutionContent)
        );

        //规则类型
        Map mapType = kv(
                ColumnUtil.F(JbOpportunityRules::getDeptId),
                ColumnUtil.F(JbOpportunityRules::getExecutionType),
                rules
        );
        toKey(list, mapType,
                ColumnUtil.F(JbOpportunityRulesVO::getDeptId),
                ColumnUtil.F(JbOpportunityRulesVO::getExecutionType)
        );

        return AjaxResult.success(list);
    }

    /**
     * 查询线上小组部门商机规则列表
     *
     * @param page    分页查询对象
     * @param sysDept 系统部门对象
     * @return
     */
    @ApiOperation("查询线上小组部门商机规则列表")
    @GetMapping("/listAll")
    @SneakyThrows
    public AjaxResult listAll(PageParam page, SysDept sysDept)
    {
        sysDept.setDeptName(page.getKeyword());
        List<SysDept> depts = deptService.selectDeptList(sysDept);

        List<JbOpportunityRulesVO> list = BeanUtil.copyToList(depts, JbOpportunityRulesVO.class);

        //获取数据集
        List<Long> ids = ids(list, ColumnUtil.F(JbOpportunityRulesVO::getDeptId));

        //规则
        Map map = kv(
                ColumnUtil.F(JbOpportunityRules::getDeptId),
                ColumnUtil.F(JbOpportunityRules::getExecutionType),
                service.listAllByDeptIds(ids, Constants.ONLINE_DEPTTEAM_OPPORTUNITY)
        );
        toKey(list, map,
                ColumnUtil.F(JbOpportunityRulesVO::getDeptId),
                ColumnUtil.F(JbOpportunityRulesVO::getExecutionType)
        );

        //人数
        Map deptUsersNumber = kv(
                ColumnUtil.F(SysDeptVo::getDeptId),
                ColumnUtil.F(SysDeptVo::getUsersNumber),
                deptService.usersNumber(ids)
        );
        toKey(list, deptUsersNumber,
                ColumnUtil.F(JbOpportunityRulesVO::getDeptId),
                ColumnUtil.F(JbOpportunityRulesVO::getUsersNumber)
        );

        return AjaxResult.success(list);
    }

    /**
     * 导出商机规则列表
     */
    @ApiOperation("导出商机规则列表")
    @Log(title = "商机规则", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PageParam page, JbOpportunityRules jbOpportunityRules)
    {
        LambdaQueryWrapper<JbOpportunityRules> select = new LambdaQueryWrapper<>();
        IPage<JbOpportunityRules> iPage = service.page(page.b(), select);

        List<JbOpportunityRules> list = iPage.getRecords();
        ExcelUtil<JbOpportunityRules> util = new ExcelUtil<JbOpportunityRules>(JbOpportunityRules.class);
        util.exportExcel(response, list, "商机规则数据");
    }

    /**
     * 获取商机规则详细信息
     */
    @ApiOperation("获取商机规则详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(service.getById(id));
    }

    /**
     * 新增 线上小组部门商机分配规则
     */
    @ApiOperation("线上小组部门商机分配规则")
    @Log(title = "线上小组部门商机分配规则", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult addGroupRules(@RequestBody JbOpportunityRulesVO jbOpportunityRulesVO)
    {
        return add(jbOpportunityRulesVO, Constants.ONLINE_DEPTTEAM_OPPORTUNITY);
    }

    protected AjaxResult add(JbOpportunityRulesVO jbOpportunityRulesVO, String rulesCode)
    {
        LambdaQueryWrapper<JbOpportunityRules> select = new LambdaQueryWrapper<>();
        select.in(JbOpportunityRules::getDeptId, jbOpportunityRulesVO.getIds())
                .eq(JbOpportunityRules::getRulesCod, rulesCode);
        List<JbOpportunityRules> list = service.list(select);


        //修改
        Map<Long, String> map = new HashMap<>();
        for (JbOpportunityRules jbOpportunityRules : list)
        {
            jbOpportunityRules.setExecutionType(jbOpportunityRulesVO.getExecutionType());
            jbOpportunityRules.setExecutionContent(jbOpportunityRulesVO.getExecutionContent());
            map.put(jbOpportunityRules.getDeptId(), "");
        }
        if (list.size() > 0)
        {
            service.updateBatchById(list);
        }

        //新增
        List<JbOpportunityRules> adds = new ArrayList<>();
        for (Long deptId : jbOpportunityRulesVO.getIds())
        {
            if (!map.containsKey(deptId))
            {
                JbOpportunityRules jbOpportunityRules = new JbOpportunityRules();
                jbOpportunityRules.setDeptId(deptId);
                jbOpportunityRules.setRulesCod(rulesCode);
                jbOpportunityRules.setExecutionType(jbOpportunityRulesVO.getExecutionType());
                jbOpportunityRules.setExecutionContent(jbOpportunityRulesVO.getExecutionContent());
                adds.add(jbOpportunityRules);
            }
        }

        if (adds.size() > 0)
        {
            return toAjax(service.saveBatch(adds));
        }
        return success();
    }

    /**
     * 新增 线下渠道商机分配规则
     */
    @ApiOperation("线下渠道商机分配规则")
    @Log(title = "线下渠道商机分配规则", businessType = BusinessType.INSERT)
    @PostMapping("/addOfflineRules")
    public AjaxResult addOfflineRules(@RequestBody JbOpportunityRulesVO jbOpportunityRulesVO)
    {
        return add(jbOpportunityRulesVO, Constants.OFFLINE_OPPORTUNITY);
    }

    /**
     * 新增 线上小组部门商机分配规则
     */
    @ApiOperation("线上小组部门商机分配规则")
    @Log(title = "线上小组部门商机分配规则", businessType = BusinessType.INSERT)
    @PostMapping("/addPublicRules")
    public AjaxResult addPublicRules(@RequestBody JbOpportunityRulesVO jbOpportunityRulesVO)
    {
        return add(jbOpportunityRulesVO, Constants.ONLINE_PUBLIC_OPPORTUNITY);
    }

    /**
     * 修改商机规则
     */
    @ApiOperation("修改商机规则")
    @Log(title = "商机规则", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody JbOpportunityRules jbOpportunityRules)
    {
        return toAjax(service.updateById(jbOpportunityRules));
    }

    /**
     * 删除商机规则
     */
    @ApiOperation("删除商机规则")
    @Log(title = "商机规则", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(service.removeByIds(Arrays.asList(ids)));
    }
}
